package homework.billing.timer;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class LabelClock {

    private Timer timer;

    private ArrayList<Listener> listeners;
    private volatile int seconds;

    public LabelClock(Listener... listenerList) {
        seconds = 0;
        listeners = new ArrayList<Listener>();
        for(int i=0;i<listenerList.length;i++) {
            listeners.add(listenerList[i]);
        }

        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ++seconds;
                noifyListener();
            }
        });
    }

    public void addListener(Listener l) {
        listeners.add(l);
    }

    public boolean start() {
        if(!timer.isRunning()) {
            timer.start();
            return true;
        }
        return false;
    }

    public boolean stop() {
        if(timer.isRunning()) {
            timer.stop();
            return true;
        }
        return false;
    }

    public void resetSecond() {
        this.seconds = 0;
        noifyListener();
    }

    public void noifyListener() {
        for(int i=0;i<listeners.size();i++) {
            listeners.get(i).receiveTime(seconds);
        }
    }

    public int getSecond() {
        return seconds;
    }

    private String fillTime(float v) {
        String s = String.format("%.0f", v);
        if(s.length() == 1)
            s = "0" + s;
        return s;
    }

    public String formatTime() {
        float h =  seconds / 3600;
        float m = seconds % 3600 / 60;
        float s = seconds % 60;

        return fillTime(h)+":"+fillTime(m)+":"+fillTime(s);
    }

    public boolean isRunning() {
        return timer.isRunning();
    }
}
